<!--
 * @Author: shiweizhen 787632169@qq.com
 * @Date: 2025-06-19 10:42:14
 * @LastEditors: shiweizhen 787632169@qq.com
 * @LastEditTime: 2025-07-24 09:35:30
 * @Description: 
 * Copyright (c) 2025-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
-->
<template>
  <div ref="container" class="h-[100%] w-[100%]"></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'

import { createUniver, defaultTheme, FUniver, IDisposable, LocaleType, merge, Univer, IWorkbookData } from '@univerjs/presets';
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
import { UniverSheetsUIPlugin } from '@univerjs/presets/preset-sheets-core';
import UniverPresetSheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN';
import { UniverSheetsFilterPreset } from '@univerjs/presets/preset-sheets-filter';
import UniverPresetSheetsFilterZhCN from '@univerjs/presets/preset-sheets-filter/locales/zh-CN';
import '@univerjs/presets/lib/styles/preset-sheets-core.css';
import '@univerjs/presets/lib/styles/preset-sheets-filter.css'
import ButtonIcon from './components/button-icon.vue';
import FilterIcon from './components/filter-icon.vue';
import FlushIcon from './components/flush-icon.vue';
import MiddlewareSidebar from './components/middleware-sidebar.vue';
import FilterSidebar from './components/filter-sidebar.vue';
import { sidebarStore } from '@/store/sidebar'
import { addSheet, delSheet, getWorkBookById, updateCalResult, updateWorkBookById } from '@/api/univer-sheet';
import { SheetPageType, UpdateCalType, UpdateWorkbookType } from '@/api/univer-sheet/types';
import _ from 'lodash/index'

const useSidebarStore = sidebarStore()
const route = useRoute()
const workbookId = route.query.id as string
const showSidebar = computed(() => useSidebarStore.show)

const container = ref<HTMLElement | null>(null)


let univerInstance: Univer | null = null
let univerAPIInstance: FUniver | null = null
let customSidebar: IDisposable
let middlewareSidebar: IDisposable
let filterSidebar: IDisposable
let linstener: IDisposable
let sheetData: IWorkbookData
onMounted(() => {
  const { univer, univerAPI } = initUniver()
  univerInstance = univer
  univerAPIInstance = univerAPI
  initData()
  linstener = linstenCommand()
})
const initUniver = () => {
  const { univer, univerAPI } = createUniver({
    locale: LocaleType.ZH_CN,
    locales: {
      [LocaleType.ZH_CN]: merge(
        {},
        UniverPresetSheetsCoreZhCN,
        UniverPresetSheetsFilterZhCN
      ),
    },
    theme: defaultTheme,
    presets: [
      UniverSheetsCorePreset({
        container: container.value as HTMLElement,
        header: false,
        toolbar: false,
        footer: false,
        contextMenu: false,
        menu: {},
        sheets: {
          scrollConfig: {}
        }
      }),
      UniverSheetsFilterPreset(),
    ]
  })

  univerAPI.registerComponent('ButtonIcon', ButtonIcon, { framework: 'vue3' })
  univerAPI.registerComponent('FilterIcon', FilterIcon, { framework: 'vue3' })
  univerAPI.registerComponent('FlushIcon', FlushIcon, { framework: 'vue3' })
  // univerAPI.registerSheetColumnHeaderExtension()
  univerAPI.createMenu({
    id: 'custom-search',
    icon: 'ButtonIcon',
    title: '配置业务层',
    tooltip: '配置业务层',
    order: 10,
    action: () => {
      useSidebarStore.toggleShow(true)
      middlewareSidebar = univerAPI.registerComponent('MiddlewareSidebar', MiddlewareSidebar, { framework: 'vue3' })
      opendMiddlewareSidebar(univerAPI)
    }
  }).appendTo(['contextMenu.mainArea', 'contextMenu.others'])

  univerAPI.createMenu({
    id: 'custom-filter',
    icon: 'FilterIcon',
    title: '筛选',
    tooltip: '筛选',
    order: 12,
    action: async () => {
      useSidebarStore.toggleShow(true)
      filterSidebar = univerAPI.registerComponent('FilterSidebar', FilterSidebar, { framework: 'vue3' })
      opendFilterSidebar(univerAPI)
    }
  }).appendTo(['contextMenu.mainArea', 'contextMenu.others'])

  univerAPI.createMenu({
    id: 'custom-flush',
    icon: 'FlushIcon',
    title: '更新计算结果',
    tooltip: '更新计算结果',
    order: 12,
    action: async () => {
      const fWorkbook = univerAPI.getActiveWorkbook();
      const fWorksheet = fWorkbook!.getActiveSheet();
      // const fWorkCell = fWorkbook!.getActiveCell();
      // isDisabled.value = fWorkCell?.getCustomMetaData()?.inputValue ? false : true
      const params: UpdateCalType = {
        workbookDataId: fWorkbook!.getId(),
        workbookSheetId: fWorksheet!.getSheetId(),
      }
      const { data } = await updateCalResult(params)
      data.forEach(item => {
        const { calculateResult, formula, excelRange } = item
        const fRangeValue = fWorksheet.getRange(excelRange).getValue()
        if (fRangeValue !== calculateResult) {
          fWorksheet.getRange(excelRange).setValue({ v: calculateResult, custom: { inputValue: formula }, s: { bg: { rgb: '#e8f3ff' } } }).setNumberFormat('#,##0')
        }
      })
    }
  }).appendTo(['ribbon.start.others'])

  // univerAPI.addEvent(univerAPI.Event.CellPointerDown, (params) => {
  //   console.log(params, 'params');
  //   isDisabled.value = true
  // })
  return { univer, univerAPI }
}

const opendMiddlewareSidebar = (univerAPI: FUniver) => {
  customSidebar = univerAPI.openSidebar({
    id: 'middleware-sidebar',
    header: { title: '配置业务层' },
    width: '600px',
    children: {
      label: {
        name: 'MiddlewareSidebar',
        props: {
          univerAPIInstance,
        }
      },
    },
    onClose: () => {
      useSidebarStore.toggleShow(false)
    }
  })
}

const opendFilterSidebar = (univerAPI: FUniver) => {
  customSidebar = univerAPI.openSidebar({
    id: 'filter-sidebar',
    header: { title: '筛选' },
    width: '300px',
    children: {
      label: {
        name: 'FilterSidebar',
        props: {
          univerAPIInstance,
        }
      },
    },
    onClose: () => {
      useSidebarStore.toggleShow(false)
    }
  })
}

const initData = async () => {
  const res = await getWorkBookById(workbookId);
  sheetData = res.data as IWorkbookData;
  univerAPIInstance!.createWorkbook(sheetData)
  // const fWorkbook = univerAPIInstance!.getActiveWorkbook();
  // const fWorksheet = fWorkbook!.getActiveSheet();
  // fWorksheet.setHiddenGridlines(true)
  // const permission = univerAPIInstance!.getPermission()
  // const workbookEditablePermission = permission.permissionPointsDefinition.WorkbookEditablePermission
  // permission.setWorkbookPermissionPoint(workbookId, workbookEditablePermission, false)
  // permission.setPermissionDialogVisible(false)
}

const linstenCommand = () => {
  return univerAPIInstance!.addEvent(univerAPIInstance!.Event.CommandExecuted, async (event) => {
    const { options, ...commandInfo } = event;

    if (commandInfo.type !== 2 || options?.fromCollab || options?.onlyLocal || commandInfo.id === 'doc.mutation.rich-text-editing') {
      return;
    }
    if (commandInfo.id === "sheet.mutation.insert-sheet") {
      const data: SheetPageType = {
        id: commandInfo.params.sheet.id,
        workbookDataId: workbookId,
        dataJson: JSON.stringify(commandInfo.params.sheet)
      };
      await insertSheet(data);
      return;
    }
    if (commandInfo.id === "sheet.mutation.remove-sheet") {
      await deleteSheet(commandInfo.params.subUnitId);
      return;
    }

    debounceFun()
  })
}


const debounceFun = _.debounce(async () => {
  const fWorkbook = univerAPIInstance!.getActiveWorkbook()!;
  const fWorksheet = fWorkbook.getActiveSheet();
  const sheetSnapshot = fWorksheet.getSheet().getSnapshot();
  const snapshot = fWorkbook.save();
  const data: UpdateWorkbookType = {
    id: fWorkbook.getId(),
    sheetId: fWorksheet.getSheetId(),
    styles: JSON.stringify(snapshot.styles),
    sheetJson: JSON.stringify(sheetSnapshot)
  }
  await setValues(data)
}, 1000)


const setValues = async (data: UpdateWorkbookType) => {
  await updateWorkBookById(data)
}

const insertSheet = async (data: SheetPageType) => {
  await addSheet(data)
}

const deleteSheet = async (id: string) => {
  await delSheet(id)
}

watch(() => showSidebar.value, (newValue) => {
  if (!newValue) {
    customSidebar?.dispose()
    middlewareSidebar?.dispose()
    filterSidebar?.dispose()
  }
})


onBeforeUnmount(() => {
  univerInstance?.dispose()
  univerAPIInstance?.dispose()
  linstener?.dispose()
  univerInstance = null
  univerAPIInstance = null
})

</script>